package eureka.ui.home;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eureka.domain.auction.Auction;
import eureka.domain.auction.AuctionState;
import eureka.domain.book.BookItem;
import eureka.domain.book.BookState;
import eureka.exceptions.DatabaseException;
import eureka.service.auction.IAuctionService;
import eureka.service.auction.impl.AuctionService;
import eureka.service.book.IBookService;
import eureka.service.book.impl.BookService;
import util.lang.RefValue;

/**
 * Servlet implementation class Homepage
 */
@WebServlet("/Homepage")
public class Homepage extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private IBookService bookService = new BookService();
	private IAuctionService auctionService = new AuctionService();

	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Homepage() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		RefValue<Long> count = new RefValue<Long>();
		
		List<BookItem> recentOnshelfList;
		try {
			recentOnshelfList = bookService.searchBooks("", 0, 0, 0, BookState.OnShelf, null, null, null, null, 0, 5, count);
		} catch (DatabaseException e) {
			response.sendError(500);
			return;
		}
		request.setAttribute("recentOnshelfList", recentOnshelfList);
		
		List<Auction> recentAuctionList;
		
		try {
			recentAuctionList = auctionService.getAuctions(0, 0, 0, AuctionState.Ongoing, 0, 0, 5);
		} catch (DatabaseException e) {
			response.sendError(500);
			return;
		}
		request.setAttribute("recentAuctionList", recentAuctionList);
		
		request.getRequestDispatcher("homepage.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
